package cn.joyfulmedia.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ValidatorUtils {

    private final static int UID_LENGTH = 32;

    private final static Pattern MOBILE_PATTERN = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
    private final static Pattern EMAIL_PATTERN = Pattern.compile("^[\\w\\-\\.]+@[\\w\\-\\.]+(\\.\\w+)+$");

    /**
     * 判断是否电话号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Matcher m = MOBILE_PATTERN.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isEmail(String email) {
        boolean flag = false;
        try {
            Matcher m = EMAIL_PATTERN.matcher(email);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 判断是否纯数字
     *
     * @param s
     * @return
     */
    public final static boolean isNumeric(String s) {
        if (s != null && !"".equals(s.trim())) {
            return s.matches("^[0-9]*$");
        }
        return false;
    }

    /**
     * 判断是否为ip v4地址
     *
     * @param text
     * @return
     */
    public final static boolean isIpv4Addr(String text) {
        if (StringUtils.isNotBlank(text)) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4 ]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }

        }
        return false;
    }

    /**
     * 判断uid是否有效
     *
     * @param uid
     * @return
     */
    public final static boolean isValidUid(String uid) {
        if (StringUtils.isBlank(uid) || uid.length() < UID_LENGTH) {
            return false;
        }
        return true;
    }

    /**
     * 检查ID是否有效，id必须大于0
     * @param id
     * @return
     */
    public final static boolean isValidId(Integer id) {
        if (id != null && id.intValue() > 0) {
            return true;
        }
        return false;
    }
}
